var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

//根据条件查询物流配送记录
exports.queryByCondition = function (condition, completeFun) {
    var entity = entityCollection.getEntity("DeliveryRecord");
    entity.findOne(condition, null, function (err, record) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, record);
        }
    });
};

// 根据仓库ID查询物流配送记录
exports.queryDeliveryRecords = function (wareHouse) {
    var entity = entityCollection.getEntity("DeliveryRecord");
    return entity.Entity.find(
        {WareHouse: wareHouse},
        {WareHouse: 1, Container: 1, Status: 1, Qty: 1, ReadyTime: 1, StockPerson: 1, DemandDepartment: 1}
    ).sort(
        {ReadyTime: -1}
    ).populate([
        {path: 'DemandDepartment', select: 'Code Name'},
        {path: 'Container', select: 'Code Name'},
        {path: 'StockPerson', select: 'Code Name'}
    ]);
};

// 更新配送记录
exports.update = function (records) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("DeliveryRecord");
    entity.save(records, function (err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '更新配送记录错误';
            newErr.message = '更新配送记录失败，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(result);
    });

    return deferred.promise;
};

//货架找超市
exports.queryWareHouseByContainer = function (containerId, completeFun) {
    var entity = entityCollection.getEntity("DeliveryRecord");
    entity.findOne({Container: containerId}, [{
        path: 'WareHouse',
        select: 'Code Name'
    }], function (err, record) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, record);
        }
    });
};
